<template>
  <div class="profile-main">
    <el-card class="box-card">
      <template #header>
        <div class="clearfix">
          <span>尊敬的会员</span>
          <el-button type="primary" size="mini" style="float: right">购买</el-button>
        </div>
      </template>
      <div>
        <div class="profile-summary">
          <el-row>
            <el-col :span="8">现金：￥{{ userInfo.money }}</el-col>
            <el-col :span="8">积分：{{ userInfo.points }}</el-col>
            <el-col :span="8">优惠券：{{ coupons.length }}</el-col>
          </el-row>
        </div>
        <el-divider></el-divider>
        <div class="order-status">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="全部订单" name="all">
              <div v-if="orders.all.length || orders.hotel.all.length">
                <div v-for="order in orders.all" :key="order.id" class="order-item">
                  <p>订单号: {{ order.orderNo }}</p>
                  <p>航班ID: {{ order.flightID }}</p>
                  <p>价格: {{ order.price }}</p>
                  <p>舱位类型: {{ order.spaceType }}</p>
                  <p>总价: {{ order.tprice }}</p>
                  <p>购买数量: {{ order.buyNum }}</p>
                  <p>订单时间: {{ order.orderTime }}</p>
                </div>
                <div v-for="order in orders.hotel.all" :key="order.id" class="order-item">
                  <p>订单号: {{ order.id }}</p>
                  <p>酒店ID: {{ order.hotelID }}</p>
                  <p>房间号: {{ order.roomNum }}</p>
                  <p>房间类型: {{ order.roomType }}</p>
                  <p>入住时间: {{ order.rztime }}</p>
                  <p>退房时间: {{ order.tftime }}</p>
                  <p>支付方式: {{ order.payWay }}</p>
                  <p>价格: {{ order.price }}</p>
                </div>
              </div>
              <div v-else class="no-data">暂时没有相关订单</div>
            </el-tab-pane>
            <el-tab-pane label="未出行" name="upcoming">
              <div v-if="orders.upcoming.length || orders.hotel.upcoming.length">
                <div v-for="order in orders.upcoming" :key="order.id" class="order-item">
                  <p>订单号: {{ order.orderNo }}</p>
                  <p>航班ID: {{ order.flightID }}</p>
                  <p>价格: {{ order.price }}</p>
                  <p>舱位类型: {{ order.spaceType }}</p>
                  <p>总价: {{ order.tprice }}</p>
                  <p>购买数量: {{ order.buyNum }}</p>
                  <p>订单时间: {{ order.orderTime }}</p>
                  <el-button type="success" @click="confirmPayment(order)">支付</el-button>
                  <el-button type="danger" @click="confirmHotelCancellation(order)">退订</el-button>
                </div>
                <div v-for="order in orders.hotel.upcoming" :key="order.id" class="order-item">
                  <p>订单号: {{ order.id }}</p>
                  <p>酒店ID: {{ order.hotelID }}</p>
                  <p>房间号: {{ order.roomNum }}</p>
                  <p>房间类型: {{ order.roomType }}</p>
                  <p>入住时间: {{ order.rztime }}</p>
                  <p>退房时间: {{ order.tftime }}</p>
                  <p>支付方式: {{ order.payWay }}</p>
                  <p>价格: {{ order.price }}</p>
                  <el-button type="success" @click="confirmPayment(order)">支付</el-button>
                  <el-button type="danger" @click="confirmHotelCancellation(order)">退订</el-button>
                </div>
              </div>
              <div v-else class="no-data">暂时没有相关订单</div>
            </el-tab-pane>
            <el-tab-pane label="待付款" name="pending">
              <div v-if="orders.pending.length || orders.hotel.pending.length">
                <div v-for="order in orders.pending" :key="order.id" class="order-item">
                  <p>订单号: {{ order.orderNo }}</p>
                  <p>航班ID: {{ order.flightID }}</p>
                  <p>价格: {{ order.price }}</p>
                  <p>舱位类型: {{ order.spaceType }}</p>
                  <p>总价: {{ order.tprice }}</p>
                  <p>购买数量: {{ order.buyNum }}</p>
                  <p>订单时间: {{ order.orderTime }}</p>
                  <el-button type="success" @click="confirmPayment(order)">支付</el-button>
                  <el-button type="danger" @click="confirmCancellation(order)">退订</el-button>
                </div>
                <div v-for="order in orders.hotel.pending" :key="order.id" class="order-item">
                  <p>订单号: {{ order.id }}</p>
                  <p>酒店ID: {{ order.hotelID }}</p>
                  <p>房间号: {{ order.roomNum }}</p>
                  <p>房间类型: {{ order.roomType }}</p>
                  <p>入住时间: {{ order.rztime }}</p>
                  <p>退房时间: {{ order.tftime }}</p>
                  <p>支付方式: {{ order.payWay }}</p>
                  <p>价格: {{ order.price }}</p>
                  <el-button type="success" @click="confirmPayment(order)">支付</el-button>
                  <el-button type="danger" @click="confirmCancellation(order)">退订</el-button>
                </div>
              </div>
              <div v-else class="no-data">暂时没有相关订单</div>
            </el-tab-pane>
            <el-tab-pane label="已支付" name="payed">
              <div v-if="orders.payed.length || orders.hotel.payed.length">
                <div v-for="order in orders.payed" :key="order.id" class="order-item">
                  <p>订单号: {{ order.orderNo }}</p>
                  <p>航班ID: {{ order.flightID }}</p>
                  <p>价格: {{ order.price }}</p>
                  <p>舱位类型: {{ order.spaceType }}</p>
                  <p>总价: {{ order.tprice }}</p>
                  <p>购买数量: {{ order.buyNum }}</p>
                  <p>订单时间: {{ order.orderTime }}</p>
                </div>
                <div v-for="order in orders.hotel.payed" :key="order.id" class="order-item">
                  <p>订单号: {{ order.id }}</p>
                  <p>酒店ID: {{ order.hotelID }}</p>
                  <p>房间号: {{ order.roomNum }}</p>
                  <p>房间类型: {{ order.roomType }}</p>
                  <p>入住时间: {{ order.rztime }}</p>
                  <p>退房时间: {{ order.tftime }}</p>
                  <p>支付方式: {{ order.payWay }}</p>
                  <p>价格: {{ order.price }}</p>
                </div>
              </div>
              <div v-else class="no-data">暂时没有相关订单</div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </el-card>
    <el-dialog title="确认支付" v-model="dialogVisible" width="30%" @close="resetDialog">
      <div>
        <span>确认支付订单总价为￥{{ finalPrice }}？</span>
        <el-divider></el-divider>
        <el-select v-model="selectedCoupon" placeholder="请选择优惠券" @change="updateFinalPrice">
          <el-option v-for="coupon in coupons" :key="coupon.id" :label="coupon.name" :value="coupon"
                     :disabled="!isCouponValid(coupon)">
          </el-option>
        </el-select>
        <div v-if="!selectedCoupon && coupons.length">未选择优惠券</div>
      </div>
      <template v-slot:footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePayment">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog title="确认退订" v-model="cancelDialogVisible" width="30%" @close="resetDialog">
      <span>确认退订订单号为{{ selectedOrder.orderNo }}的订单？</span>
      <template v-slot:footer>
        <el-button @click="cancelDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCancellation">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog title="确认退订" v-model="hotelCancelDialogVisible" width="30%" @close="resetDialog">
      <span>确认退订订单号为{{ selectedOrder.id }}的订单？</span>
      <template v-slot:footer>
        <el-button @click="hotelCancelDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleHotelCancellation">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getOrdersByUserId, updateOrder, deleteOrder } from '@/api/order';
import { getHotelOrderByUid, updateHotelOrder, deleteHotelOrder } from '@/api/hotelOrder';
import { getUserById, updateUser } from '@/api/user';
import { getCouponByUid } from '@/api/coupon';

const userInfo = ref({});
const orders = ref({
  all: [],
  upcoming: [],
  pending: [],
  payed: [],
  hotel: {
    all: [],
    upcoming: [],
    pending: [],
    payed: []
  }
});
const coupons = ref([]);
const activeTab = ref('all');
const dialogVisible = ref(false);
const cancelDialogVisible = ref(false);
const hotelCancelDialogVisible = ref(false);
const selectedOrder = ref({});
const selectedCoupon = ref(null);
const finalPrice = ref(0);

// 获取用户ID
const userInfoString = localStorage.getItem('userInfo');
const user = ref(JSON.parse(userInfoString));
const userId = user.value.id;

const confirmPayment = async (order) => {
  selectedOrder.value = order;
  dialogVisible.value = true;
  await loadCoupons();
  updateFinalPrice();
};

const handlePayment = async () => {
  const totalPrice = selectedOrder.value.tprice || selectedOrder.value.price;
  if (userInfo.value.money >= finalPrice.value) {
    userInfo.value.money -= finalPrice.value;
    userInfo.value.points += Math.floor(finalPrice.value / 100);

    // 更新订单状态
    selectedOrder.value.status = 'payed';
    const orderUpdateResponse = selectedOrder.value.flightID
        ? await updateOrder(selectedOrder.value)
        : await updateHotelOrder(selectedOrder.value);
    if (orderUpdateResponse.code === 1) {
      // 更新用户信息
      const userUpdateResponse = await updateUser(userInfo.value);
      if (userUpdateResponse.code === 1) {
        dialogVisible.value = false;
        await loadOrders();
      } else {
        console.error(userUpdateResponse.msg);
      }
    } else {
      console.error(orderUpdateResponse.msg);
    }
  } else {
    alert('余额不足');
  }
};

const confirmCancellation = (order) => {
  selectedOrder.value = order;
  cancelDialogVisible.value = true;
};

const handleCancellation = async () => {
  const orderDeleteResponse = await deleteOrder(selectedOrder.value.id);
  if (orderDeleteResponse.code === 1) {
    cancelDialogVisible.value = false;
    await loadOrders();
  } else {
    console.error(orderDeleteResponse.msg);
  }
};

const confirmHotelCancellation = (order) => {
  selectedOrder.value = order;
  hotelCancelDialogVisible.value = true;
};

const handleHotelCancellation = async () => {
  const orderDeleteResponse = await deleteHotelOrder(selectedOrder.value.id);
  if (orderDeleteResponse.code === 1) {
    hotelCancelDialogVisible.value = false;
    await loadOrders();
  } else {
    console.error(orderDeleteResponse.msg);
  }
};

const resetDialog = () => {
  selectedOrder.value = {};
  selectedCoupon.value = null;
  finalPrice.value = 0;
};

const loadOrders = async () => {
  const userResponse = await getUserById(userId);
  if (userResponse.code === 1) {
    userInfo.value = userResponse.data;
  } else {
    console.error(userResponse.msg);
  }

  const orderResponse = await getOrdersByUserId(userId);
  if (orderResponse.code === 1) {
    orders.value.all = orderResponse.data;
    orders.value.upcoming = orderResponse.data.filter(order => order.status === 'upcoming');
    orders.value.pending = orderResponse.data.filter(order => order.status === 'pending');
    orders.value.payed = orderResponse.data.filter(order => order.status === 'payed');
  } else {
    console.error(orderResponse.msg);
  }

  const hotelResponse = await getHotelOrderByUid(userId);
  if (hotelResponse.code === 1) {
    orders.value.hotel.all = hotelResponse.data;
    orders.value.hotel.upcoming = hotelResponse.data.filter(order => order.status === 'upcoming');
    orders.value.hotel.pending = hotelResponse.data.filter(order => order.status === 'pending');
    orders.value.hotel.payed = hotelResponse.data.filter(order => order.status === 'payed');
  } else {
    console.error(hotelResponse.msg);
  }
};

const loadCoupons = async () => {
  const couponResponse = await getCouponByUid(userId);
  if (couponResponse.code === 1) {
    coupons.value = couponResponse.data;
  } else {
    console.error(couponResponse.msg);
  }
};

const updateFinalPrice = () => {
  const totalPrice = selectedOrder.value.tprice || selectedOrder.value.price;
  if (!selectedCoupon.value) {
    finalPrice.value = totalPrice;
  } else {
    const { discount_type, discount_value, threshold_amount } = selectedCoupon.value;
    if (threshold_amount > totalPrice) {
      finalPrice.value = totalPrice;
      alert('该优惠券不满足使用条件');
    } else {
      if (discount_type === 1) {
        const times = Math.floor(totalPrice / threshold_amount);
        finalPrice.value = totalPrice - times * discount_value;
      } else if (discount_type === 2) {
        finalPrice.value = totalPrice * (discount_value / 10);
      } else if (discount_type === 3) {
        finalPrice.value = totalPrice - discount_value;
      }
    }
  }
};

const isCouponValid = (coupon) => {
  const totalPrice = selectedOrder.value.tprice || selectedOrder.value.price;
  return totalPrice >= coupon.threshold_amount;
};

onMounted(() => {
  loadOrders();
});
</script>




<style scoped>
.profile-main {
  height: 90vh;
  overflow-y: auto;
  padding: 20px;
  background-color: #f9f9f9;
}

.profile-summary {
  padding: 10px 0;
}

.order-status {
  padding: 20px 0;
}

.no-data {
  text-align: center;
  padding: 20px;
  color: #888;
}

.order-item {
  padding: 10px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fff;
  margin-bottom: 10px;
}

.el-card {
  margin-bottom: 20px;
}

.el-button {
  margin-top: 10px;
}
</style>
